package com.fottas.adware.payment.config;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.fottas.adware.core.WXConfig;
import com.fottas.adware.payment.app.model.WXPayRequest;
import com.fottas.adware.factory.WxFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * 初始化支付
 */
@Component
@Configuration
@EnableConfigurationProperties({AliPayProperties.class, WxPayProperties.class})
public class PayConfig {

    //阿里支付属性
    private AliPayProperties aliPay;

    //微信支付属性
    private WxPayProperties wxPay;

    public PayConfig(AliPayProperties aliPay, WxPayProperties wxPay) {
        this.wxPay = wxPay;
        this.aliPay = aliPay;
        this.initAliConfig();
        this.initWxConfig();

    }

    /**
     * 微信相关配置初始化
     */
    private void initWxConfig() {
        WXConfig config = WXConfig.builder()
                .appId(wxPay.getAppId())
                .mchId(wxPay.getMchId())
                .notifyUrl(wxPay.getNotifyUrl())
                .build();
        WxFactory.setOptions(config);
    }

    /**
     * 支付宝相关配置初始化
     * @return
     */
    private void initAliConfig() {
        Config config = new Config();
        config.protocol = aliPay.getProtocol();
        config.gatewayHost = aliPay.getGatewayHost();
        config.signType = aliPay.getSignType();
        config.appId = aliPay.getAppId();
        /**
         * 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
         */
        config.merchantPrivateKey = aliPay.getMerchantPrivateKey();
        config.alipayPublicKey = aliPay.getAliPayPublicKey();
        config.notifyUrl = aliPay.getNotifyUrl();
        config.encryptKey = aliPay.getEncryptKey();
        Factory.setOptions(config);
    }
}
